package cp.test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class UDPStreamWorker implements Runnable {

	private volatile boolean running = true, mainloop = true;
	private Thread tp;
	private int port;
	private InetAddress ip;
	private DatagramSocket serverSocket;
    byte value = (byte) 0;

	UDPStreamWorker(int port, String ip) throws UnknownHostException {
		tp = new Thread(this);
		this.ip = InetAddress.getByName(ip);
		this.port = port;
	}

	public void start() {
		running = true;
		mainloop = true;
		tp.start();
	}

	public void stop() {
		running = false;
		mainloop = false;
	}

	public void run() {
		try {
			while (mainloop) {
				serverSocket = new DatagramSocket(port);
				System.out.println("UDP Server created " + port);
				running = true;

				while (running) {
					byte[][] data = createArray();
					
					for (int i = 0; i < data.length; i++) {
						DatagramPacket senddata = new DatagramPacket(data[i],
								data[i].length, ip, port);
						serverSocket.send(senddata);
					}
				}

				serverSocket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private byte[][] createArray() {

		byte[][] tempdata = new byte[120][640*3*4];
		
		for(int i = 0; i < tempdata.length; i++){
		    
		    for(int k = 0; k < 640 * 4; k++){
		        
	                for (int d = 0; d < 3; d++) {
	                        tempdata[i][k] = (value);
	                }
		        
		    }
		    
		}
		value+=20;
		return tempdata;
	}

}
